<?php

namespace App\Http\Controllers;

use DB;
use Cache;
use Redis;

class CommonController extends ApiController
{
    protected function articleFieldExceptContent()
    {
        return DB::connection('sqlsrv')->table('articles')
            ->select('article_id as id', 'article_title as title', 'article_logo as thumbnail_url',
                'article_writer as origin', 'article_whoadd as author', 'article_addtime as created_at')
            ->where('article_active', 1);
    }

    protected function convertArticleField()
    {
        return $this->articleFieldExceptContent()
            ->addSelect('article_body as content');
    }

    protected function convertColumnField()
    {
        return DB::connection('sqlsrv')->table('lanmu')
            ->select('lanmu_id as column_id', 'lanmu_name as column_name', 'lanmu_father as parent_id')
            ->where('lanmu_language', '=', 'zh-cn')
            ->where('lanmu_active', '=', 1);
    }

    protected function getArticleById($id)
    {
        $key = 'articles/'.$id;

        if (Cache::has($key)) {
            return Cache::get($key);
        }

        $article = $this->convertArticleField()
            ->where('article_id', '=', $id)
            ->first();

        // 缓存文章详情
        $minutes = 60*24*60;
        Cache::put($key, $article, $minutes);

        return $article;
    }

    protected function wrapArticleExceptContent($id)
    {
        $article = $this->getArticleById($id);

        var_dump($article);
        // unset($article->content);
        // todo
        exit;
    }

    protected function getColumn()
    {
        $columns = DB::connection('sqlsrv')->table('lanmu')
            ->select('lanmu_id as column_id', 'lanmu_name as column_name')
            ->where('lanmu_language', 'zh-cn')
            ->take(3)
            ->get();
        return $columns;
    }

    protected function fetchUser($uid)
    {
        $user = Redis::hgetall("users:{$uid}");

        unset($user['password'], $user['created_at'], $user['updated_at']);

        return $user;
    }

    protected function checkUserArticleStar($userId, $articleId)
    {
        $rank = Redis::zrank("users:{$userId}:stars", "articles:{$articleId}");

        if ($rank === null) {
            return false;
        }

        return true;
    }

    protected function checkUserCommentFavour($userId, $commentId)
    {
        return Redis::sismember("users:{$userId}:favours", $commentId);
    }

    protected function getOwnerId()
    {
        $this->authorizer->validateAccessToken();

        return $this->authorizer->getResourceOwnerId();
    }

    protected function matchTag($subject)
    {
        $allTag = unserialize(Redis::get('api:tags'));

        $tagArr = [];
        foreach ($allTag as $value) {
            preg_match('#'.$value.'#', $subject, $matches);
            if ($matches) {
                $tagArr[] = $matches[0];
            }
        }

        return implode(',', $tagArr);
    }

    protected function fetchCommentList($key, $quantity = 2)
    {
        // offset = 0
        return $this->getCommentList($key, 0, $quantity);
    }

    protected function getCommentList($key, $offset, $limit)
    {
        $commentIdArr = Redis::zrevrange($key, $offset, $limit - 1);

        $comments = array();
        foreach ($commentIdArr as $commentId) {
            $comments[] = $this->fetchCommentByIdentifier($commentId);
        }

        return $comments;
    }

    protected function fetchCommentByIdentifier($commentId)
    {
        $comment = Redis::hgetall("comments:{$commentId}");

        $comment['user'] = $this->fetchUser($comment['user_id']);

        $comment['is_favoured'] = $this->isFavoured($commentId);

        $comment['replies'] = $this->fetchReply($commentId);

        return $comment;
    }

    protected function isFavoured($commentId)
    {
        if (! $this->accessToken) {
            return false;
        }

        $uid = $this->getOwnerId();

        return $this->checkUserCommentFavour($uid, $commentId);
    }

    protected function fetchReply($commentId)
    {
        $replyIdArr = Redis::zrevrange("comments:{$commentId}:replies", 0, 1);

        $replies = [];
        foreach ($replyIdArr as $replyId) {
            $reply = Redis::hgetall("replies:{$replyId}");

            $reply['user'] = $this->fetchUser($reply['user_id']);

            $replies[] = $reply;
        }

        return $replies;
    }

    protected function fetchTagForArticle($articleId)
    {
        // get the article title by article id
        $title = $this->getArticleById($articleId)->title;

        $tag = $this->matchTag($title);

        if ($tag != '') {
            return $tag;
        }

        $tag = Redis::zrevrange("sisi_articles:{$articleId}:comment_tags", 0, 0);

        return isset($tag[0]) ? $tag[0] : '';
    }

    /**
     * 增加数据模型分页
     *
     * @param  object $model 需要分页的数据模型
     * @return void
     */
    protected function addPagination($model)
    {
        // 起始页，默认第一页
        $page = request('page', 1);
        $page = intval($page);

        if (! is_int($page) || $page <= 0) {
            $page = 1;
        }
        // 每页显示数据条目，默认每页20条
        $perPage = request('per_page', 20);
        $perPage = intval($perPage);

        if (! is_int($perPage) || $perPage < 1 || $perPage > 100) {
            $perPage = 20;
        }
        // skip -- offset , take -- limit
        $model->skip(($page - 1) * $perPage)->take($perPage);
    }

    protected function usePagination()
    {
        // 获取分页参数
        $page = request('page', '1');
        $perPage = request('per_page', '5');
        if ($perPage < 1 || $perPage > 100) {
            $perPage = 5;
        }

        $offset = ($page - 1) * $perPage;
        if ($offset < 0) {
            $offset = 0;
        }

        $limit = $offset + $perPage;

        return [$offset, $limit];
    }

}